package com.bdqn;

import com.bdqn.pojo.TUser;
import com.bdqn.pojo.User;
import com.bdqn.service.UserService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.*;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@SpringBootTest
@RunWith(SpringRunner.class)
public class RedisTemplateTester {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private UserService userService;

    @Test
    public void testString() {
        stringRedisTemplate.opsForValue().set("name", "czkt");
        Assert.assertEquals("czkt", stringRedisTemplate.opsForValue().get("name"));
    }

    @Test
    public void testObj() {
        TUser TUser = new TUser("xuchao", "123456", 1, null);
        ValueOperations<String, TUser> operations = redisTemplate.opsForValue();
        operations.set("ktjy", TUser);
        TUser u = operations.get("ktjy");
        System.out.println(u.getName());
    }

    @Test
    public void testExpire() throws InterruptedException {
        TUser TUser = new TUser("cskt", "123456", 1, null);
        ValueOperations<String, TUser> operations = redisTemplate.opsForValue();
        operations.set("expire", TUser, 100, TimeUnit.MILLISECONDS);
        Thread.sleep(1000); //暂停该线程1000毫秒
        boolean exists = redisTemplate.hasKey("expire");
        if (exists) {
            System.out.println("exists is true");
        } else {
            System.out.println("exists is false");
        }
    }

    @Test
    public void testHash() {
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        hash.put("hash", "name", "ktjiaoyu");
        String value = (String) hash.get("hash", "name");
        System.out.println("hash name'value :" + value);
    }

    @Test
    public void testList() {
        ListOperations<String, String> list = redisTemplate.opsForList();
        list.leftPush("list", "accp");
        list.leftPush("list", "bdqn");
        list.leftPush("list", "czkt");
        String value = (String) list.leftPop("list");
        System.out.println("list value :" + value.toString());
    }

    @Test
    public void testGetUser() {
        User user = userService.getUser(2L);
        System.out.println("user.usrName:" + user.getUsrName());
    }
}
